package com.googlecode.flealancemarket.tapestry.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;

/**
 * General purpose finder
 * It can find any object in any collection. 
 * Search criterion is equality of propertyValue parameter with actual value of that property 
 * in collection elements.
 * 
 * Properties are being accessed through a getter, which naturally must be available
 * Field access is not provided, nor it should be!!
 * 
 * @author Goran Jovic <goranjovic@gmail.com/>
 * @since Sep 14, 2008
 **/
public class UniversalFinder {
	
	public <T,P> T find(Collection<T> collection, String propertyName, P propertyValue) {
		
		
		try {
			
			Class<?> elementType = collection.iterator().next().getClass();
			String getterName = "get"+propertyName.substring(0, 1).toUpperCase()+propertyName.substring(1);
			System.out.println(getterName);
			Method getter = elementType.getMethod(getterName, null);
			for(T t : collection){
				Object actualValue = getter.invoke(t, null);
				System.out.println(actualValue);
				if(propertyValue.equals(actualValue)){
					return t;
				}
			}
			System.out.println("Error! It just aint here!!");
			return null;
		} catch (NullPointerException e) {
			return null;
		}catch (Exception e) {
			System.out.println("Error! Run to the hills!!!");
			System.out.println(e.getClass());
			return null;
		}
	}

}
